<?php

$path=dirname(realpath($_SERVER['SCRIPT_FILENAME']));
$path_parts = pathinfo($path);
$p = str_replace("wp-content","",$path_parts['dirname']);	
$p = str_replace("themes","",$p);
$p = str_replace("functions","",$p);
$p = str_replace("shopperpress","",$p);
$p = str_replace("\\\\","",$p);
$p = str_replace("////","",$p);
 		
require( $p.'/wp-config.php' );

 
switch($_GET['action']){


	case "changestate": {
	
	include("../_states.php");
	
	if(in_array($_GET['current'],$state_included)){
	
			
			if($_GET['current'] == "United States of America"){$states = $state_usa;}
			if($_GET['current'] == "China"){$states = $state_china;}
			if($_GET['current'] == "France"){$states = $state_france;}
			if($_GET['current'] == "Germany"){$states = $state_germany;}
			if($_GET['current'] == "United Kingdom"){$states = $state_uk;}
			if($_GET['current'] == "Spain"){$states = $state_spain;}
			if($_GET['current'] == "Scotland"){$states = $state_scotland;}
			if($_GET['current'] == "Romania"){$states = $state_romania;}

			$string = '<div class="row">
			<label class="col1">State or Province</label>
			<span class="col2"><select name="billing[state]" class="mid2">';
			
			foreach($states as $val){
				$string .= '<option value="'.$val.'">'.$val.'</option>';
			}
			
			$string .= '</select></span></div>';
			print $string;
	
	}else{
			print  '<div class="row">
			<label class="col1">State or Province</label>
			<span class="col2"><input type="text" name="billing[state]" class="mid2" size="35" maxlength="100"/></span>
			</div>        
			 ';
	}
	
		
	
	} break;

	case "addProduct": { 
 
	
		include_once("../amazon_api_class.php");
		
		//print $_GET['catid'];
		//print $_GET['asnid'];
		
		$obj = new AmazonProductAPI();
			
			try
			{				
				$result = $obj->getItemByAsin($_GET['asnid'],$_GET['country']);
			}
			catch(Exception $e)
			{
				echo $e->getMessage();
				exit();
			}
		 
    foreach($result->Items->Item as $val){
 
  
	$data['title'] 		= $val->ItemAttributes->Title;
	$data['asin'] 		= $val->ASIN;
	$data['url'] 		= $val->DetailPageURL;
	$data['qty']		= $val->ItemAttributes->NumberOfItems;
	$data['desc']		= nl2br($val->EditorialReviews->EditorialReview->Content);
	$data['image'] 		= $val->LargeImage->URL;
	$data['thumbnail']	= $val->MediumImage->URL;
	$data['images'] 	= "";
	$data['warranty']	= $val->ItemAttributes->Warranty;
	
	if($_GET['country'] =="co.uk" || $_GET['country'] =="jp"){
	
		$data['price'] 	=  substr($val->ItemAttributes->ListPrice->FormattedPrice,2,10);

		if( $data['price'] =="" ){
			$data['price'] 		= substr($val->OfferSummary->LowestNewPrice->FormattedPrice,2,10);
		}
 
	}elseif($_GET['country'] =="de" || $_GET['country'] =="fr"){

		$data['price'] 	=  str_replace(",",".",substr($val->OfferSummary->LowestNewPrice->FormattedPrice,4,10));

	}elseif($_GET['country'] =="ca"){

		$data['price'] 	=  substr($val->OfferSummary->LowestNewPrice->FormattedPrice,5,10);

	}else{
	
		if( isset($val->OfferSummary->LowestNewPrice->Amount) ){	
		$data['price'] 		= substr($val->OfferSummary->LowestNewPrice->FormattedPrice,1,10);
		$data['old_price'] 	=  substr($val->ItemAttributes->ListPrice->FormattedPrice,1,10);
		}else{
		$data['price'] 	=  substr($val->ItemAttributes->ListPrice->FormattedPrice,1,10);
		}
	}	
 

	$AFFLINK = "http://www.amazon.".$_GET['country']."/o/ASIN/%asin%/%amazon_id%";
	$AFFLINK = str_replace("%asin%",$data['asin'],$AFFLINK);
	$AFFLINK = str_replace("%amazon_id%",'YOURUSERID',$AFFLINK);	
	
	// IMAGE SETS	
	if(isset($val->ImageSets->ImageSet)){
		foreach($val->ImageSets->ImageSet as $img){
			$data['images'] .= $img->MediumImage->URL.",";
		}
	}
	
	// GET PRODUCT FEATURES
	$excerpt="<ul>";
	foreach($val->ItemAttributes->Feature as $feature){
	$excerpt .="<li>".$feature."</li>";
	}
	$excerpt.="</ul>";	

	//	GET ATTRIBUTES
	$extra_data = "<ul class=ExtraData>";
	foreach($val->ItemAttributes as $at1){foreach($at1 as $key => $att){
	$extra_data .= "<li><b>".$key."</b>: ";
		if(is_array($att)){
			foreach($att as $in){
				$extra_data .= $in;
			}
		}else{
			$extra_data .= $att;
		}
	$extra_data .= "</li>";
	}}

	$extra_data .="</ul>";
 	
	
	if(strlen($excerpt) < 10){ $excerpt = $extra_data; }		
	
		$data['desc'] 		= str_replace(":"," : ",$data['desc']);
		$excerpt 		= str_replace(":"," : ",$excerpt);
		//die($_GET['catid']."<--");
 	  $my_post = array();
	  $my_post['post_title'] 	= $data['title'];
	  $my_post['post_content'] 	= $data['desc'];
	  $my_post['post_excerpt'] 	= $excerpt;
	  $my_post['post_author'] 	= 1;
	  $my_post['post_status'] 	= "publish";
	  $my_post['post_category'] = explode(",",$_GET['catid']);
	  $my_post['tags_input'] = str_replace(" ",",",str_replace("-","",$data['title']));;
	  $POSTID = wp_insert_post( $my_post );	  
	  
	  $data['price'] 		= str_replace(",","",$data['price']);
	  $data['old_price']  	= str_replace(",","",$data['old_price']);
	  
	  // EXTRA FIELDS
	  add_post_meta($POSTID, "amazon_link", $AFFLINK);
	  add_post_meta($POSTID, "amazon_guid", $data['asin']);
	  add_post_meta($POSTID, "price", $data['price']);
	  if(isset($data['old_price']) && strlen($data['old_price']) > 1){ add_post_meta($POSTID, "old_price", $data['old_price']); }
	  add_post_meta($POSTID, "warranty", $data['warranty']);
	  
	  add_post_meta($POSTID, "image", $data['image']);
	  add_post_meta($POSTID, "images", $data['images']);	  
	  add_post_meta($POSTID, "qty", 1);	  
	  
	  
	  // CHECK FOR COMMENTS	  
	  $time = current_time('mysql', $gmt = 0);	
	    
	  if(isset($val->CustomerReviews->Review)){ foreach($val->CustomerReviews->Review as $review){

		$data = array(
			'comment_post_ID' => $POSTID,
			'comment_author' => $review->Reviewer->Name,
			'comment_author_email' => 'admin@admin.com',
			'comment_author_url' => 'http://',
			'comment_content' => nl2br($review->Content),
			//'comment_type' => ,
			'comment_parent' => 0,
			'user_ID' => 1,
			'comment_author_IP' => '127.0.0.1',
			'comment_agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)',
			'comment_date' => $review->Date,
			'comment_date_gmt' => $time,
			'comment_approved' => 1,
		);
		
		wp_insert_comment($data);
		
	  } }
 
 
	print '<div class="msg msg-ok"><p>Product Added Successfully</p></div>';
	
	}
			
			
	
	} break;
	
	
	
	case "addEbayProduct": {
	
	 
	$appid 		= $_GET['API'];  // Replace with your own AppID

	// API request variables
	$endpoint 	= 'http://svcs.ebay.com/services/search/FindingService/v1';  // URL to call
	$version 	= '1.0.0';  // API version supported by your application
	$globalid 	= $_GET['country'];  // Global ID of the eBay site you want to search (e.g., EBAY-DE)
	$query 		= $_GET['ID'];  // You will need to supply your own query
	$SafeQuery 	= urlencode($query);  // Make the query URL-friendly
	
	// Construct the findItemsByKeywords call 
	$apicall = "$endpoint?";
	$apicall .= "OPERATION-NAME=findItemsByKeywords";
	$apicall .= "&SERVICE-VERSION=$version";
	$apicall .= "&SECURITY-APPNAME=$appid";
	$apicall .= "&GLOBAL-ID=$globalid";
	$apicall .= "&keywords=$SafeQuery";
	$apicall .= "&paginationInput.entriesPerPage=2"; // items per page
	$apicall .= "&paginationInput.pageNumber=1&outputSelector(0)=SellerInfo&outputSelector(1)=StoreInfo"; // page nav
	$apicall .= "&sortOrder=CurrentPriceHighest";
	if(strlen($_GET['aff1']) > 1){
	$apicall .= "&affiliate.networkId=9";
	$apicall .= "&affiliate.trackingId=".$_GET['aff1'];
	$apicall .= "&affiliate.customId=".$_GET['aff2'];
	} 
	
	//print $apicall;
	$resp = simplexml_load_file($apicall);
	//print_r($resp);
	if($resp->paginationOutput->totalEntries =='0'){
	
	print "Product could not be added.";
	
	}

	if(strlen($resp->errorMessage->error->message) > 2){
	
	print $resp->errorMessage->error->message;
	
	}else{
	// Check to see if the response was loaded, else print an error
	 if ($resp) {
	 
		 foreach($resp->searchResult->item as $item) {	 


			  $my_post = array();
			  $my_post['post_title'] 	= $item->title;
			  $my_post['post_content'] 	= $item->subtitle;
			  $my_post['post_excerpt'] 	= $item->subtitle;
			  $my_post['post_author'] 	= 1;
			  $my_post['post_status'] 	= "publish";
			  $my_post['post_category'] = array($_GET['catid']);
			  
			  $POSTID = wp_insert_post( $my_post );	  
			  
			  
			  // EXTRA FIELDS
			  add_post_meta($POSTID, "buy_link", $item->viewItemURL);
			  add_post_meta($POSTID, "ebay_ID", $item->ID);
			  add_post_meta($POSTID, "price", $item->sellingStatus->currentPrice);		  
			  add_post_meta($POSTID, "image", $item->galleryURL); 	  
			  add_post_meta($POSTID, "qty", 1);	
			  add_post_meta($POSTID, "redirect", 1);
			  
			  print '<div class="msg msg-ok"><p>Product Added Successfully</p></div>';
		 
		 }
	 
	 }else{
	 
	 print '<div class="msg msg-error"><p>Product Import Failed. '.$resp->errorMessage->error->message.'</p></div>';
	 }
	}

	
	
	
	} break;

case "add_image_next": {

	// GET IMAGE DATA FROM THE FOLDER
	$d = dir($_GET['path']);
	while (false !== ($entry = $d->read())) {
		if (preg_match("/(\.gif$)/i", strtolower($entry)) || preg_match("/(\.jpg$)/i", strtolower($entry)) || preg_match("/(\.jpeg$)/i", strtolower($entry)) || preg_match("/(\.png$)/i", strtolower($entry))){
			$pics[] = $entry;
		}
	}
	$d->close();
	$checkbox=1;
	$numPerRow = 12;
	$numPics = count($pics);
	if(!isset($_GET['p'])){ $c_page = 0; }else { $c_page = $_GET['p']*$numPerRow; } 
	$dd = ceil($numPics/$numPerRow);

	print '<div style="padding:10px;border:1px solid #ddd; background:#efefef; width:780px;">';

	for ($i=0; $i < $numPics; $i++){ 
	if($i > $c_page-1 && $i < $c_page+$numPerRow ){
	$currThumb = $thispic + $i + 1; if(strlen($pics[$currThumb]) > 1){ ?>

	<div style="float:left; width:220px; margin:20px; margin-left:0px; border:1px solid #dddddd; background:#fff; padding:5px;">
	<div style="height:150px; overflow:hidden;">
	<a href="http://<?php echo $_GET['link'].$pics[$currThumb] ?>" target="_blank" rel="image_group"><img src="http://<?php echo $_GET['link'].$pics[$currThumb]; ?>" style="max-width:200px;" border="0" /></a>
	</div>
	<div style="background:#efefef; border:1px solid #ddd; padding:5px; margin-top:10px;">  
	<a href="http://<?php echo $_GET['link'].$pics[$currThumb] ?>" target="_blank" rel="image_group"><img src="<?php bloginfo('template_url'); ?>/images/premiumpress/led-ico/find.png" align="absmiddle"> View</a> - 
	<a href="#" onclick="document.getElementById('<?php echo $_GET['type']; ?>').value='<?php echo $pics[$currThumb]; ?>';document.getElementById('<?php echo $_GET['type']; ?>_show').innerHTML ='<img src=\'<?php bloginfo('template_url'); ?>/images/premiumpress/led-ico/accept.png\'> <?php echo $pics[$currThumb]; ?>';toggleLayer('DisplayImages');"><img src="<?php bloginfo('template_url'); ?>/images/premiumpress/led-ico/accept.png" align="absmiddle"> Select </a>
	 </div>
	<small><b><?php echo $pics[$currThumb] ?></b></small>
	</div>

	<?php $checkbox++; } } } ?>
	<div class="clearfix"></div>
	
	<div class="pagination">
	<ul>
	<li><b>Showing Page <?php echo $_GET['p']+1; ?> of <?php if($dd ==0){ echo "1"; }else{ echo $dd; }; ?></b></li>
	<?php $pc = $dd;while($pc > 0){$pnum = $pc; ?>
	<li><a href='javascript:void(0);' onClick="add_image_next(<?php echo $pnum-1; ?>,'<?php echo $_GET['path']; ?>','<?php echo $_GET['link']; ?>','<?php echo $_GET['type']; ?>','<?php echo $_GET['div']; ?>');"><?php echo $pc; ?></a></li>
	<?php $pc--; } ?>
	</ul>
	</div>

<?php } break;


}

?>